<template>
  <div>
    <div id="chat_footer" class="flex items-center p-[32px]">
      <div class="flex-grow rounded-[12px] bg-[#fff] p-[16px]">
        <div class="flex">
          <van-popover v-model:show="showEmojiBar" placement="top">
            <ChatFooterEmoji @closeEmojiBar="closeEmojiBar" @emojiClick="emojiClick" />
            <template #reference>
              <img class="ml-3 h-[24px] min-w-[24px] cursor-pointer" :src="emoji" alt="" />
            </template>
          </van-popover>
          <ChatFooterAction @closeActionBar="closeActionBar" @getFile="getFile" />
        </div>
        <CustomEdit v-show="!recording" class="mt-[10px]" ref="inputRef" @change="inputChange"
          @focus="onFocusUpdate(true)" @blur="onFocusUpdate(false)" v-model:input="messageContent"
          @trigger-at="() => { }" @keyup.ctrl.enter.prevent="switchTextMessage"
          @switchTextMessage="switchTextMessage" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import emoji from '@/assets/images/chatFooter/emoji.png'

import CustomEdit from '@/components/CustomEdit/index.vue'
import ChatFooterAction from './ChatFooterAction.vue'
import ChatFooterEmoji from './ChatFooterEmoji.vue'
import { onLongPress, useThrottleFn } from '@vueuse/core'
import { MessageType, SessionType } from '@openim/wasm-client-sdk'
import { UploaderFileListItem } from 'vant'
import useSendMessage from '@/hooks/useSendMessage'
import useConversationStore from '@/store/modules/conversation'
import { IMSDK } from '@/utils/imCommon'
import { feedbackToast } from '@/utils/common'
import emitter from '@/utils/events'
import { checkIsSafari } from '@/utils/common'
import useCreateNomalMessage from './useCreateNomalMessage'
import useCreateFileMessage from './useCreateFileMessage'

const emit = defineEmits([])
defineProps()

const conversationStore = useConversationStore()

// message
const messageContent = ref('')
const inputRef = ref()

const { createFileMessage } = useCreateFileMessage()

const { getAtList, switchNomalMessage } = useCreateNomalMessage({
  messageContent,
})
const { sendMessage } = useSendMessage()

const inputChange = useThrottleFn(() => {
  if (
    conversationStore.storeCurrentConversation.conversationType !== SessionType.Single
  ) {
    return
  }
  IMSDK.typingStatusUpdate({
    recvID: conversationStore.storeCurrentConversation.userID,
    msgTip: 'yes',
  })
}, 2000)

const onFocusUpdate = (isFocus: boolean) => {
  if (!checkIsSafari()) {
    return
  }
  setTimeout(() => emitter.emit('KEYBOARD_UPDATE'), 100)
  if (isFocus) {
    setTimeout(() => window.scroll(0, 0), 101)
  }
}

const switchTextMessage = async () => {
  const message = await switchNomalMessage()

  if (!message?.textElem?.content) {
    feedbackToast({
      message: '请输入内容',
      error: message,
    })
    return
  }
  if (message) {
    sendMessage({ message })
  }
  resetState()
}

const emojiClick = (str: string) => {
  const parser = new DOMParser()
  const doc = parser.parseFromString(str, 'text/html')
  const nodes = Array.from(doc.body.childNodes)
  inputRef.value.insertAtCursor(nodes)
  closeEmojiBar()
}

const resetState = () => {
  messageContent.value = ''
  conversationStore.updateQuoteMessage()
  inputRef.value.clear()
}

// recording
const recording = ref(false)
const recordingBtnRef = ref()
const recordingOverlayRef = ref()

const onMenuLongPressCall = () => {
  recordingOverlayRef.value.isShowOverlay()
}

onLongPress(recordingBtnRef, onMenuLongPressCall, { modifiers: { prevent: true } })

// action bar
const showActionBar = ref(false)
const showEmojiBar = ref(false)

const closeActionBar = () => {
  showActionBar.value = false
}
const closeEmojiBar = () => {
  showEmojiBar.value = false
}

const getFile = async (uploadData: UploaderFileListItem) => {
  let messageType = MessageType.FileMessage
  if (uploadData.file?.type.includes('image')) {
    messageType = MessageType.PictureMessage
  }
  if (uploadData.file?.type.includes('video')) {
    messageType = MessageType.VideoMessage
  }
  const { error, message } = await createFileMessage(uploadData.file!, messageType)
  if (error || !message) {
    feedbackToast({ error, message: error })
    return
  }
  sendMessage({
    message,
  })
}

watch(
  () => conversationStore.storeQuoteMessage,
  (val) => {
    if (val) {
      inputRef.value.inputRef.focus()
    }
  },
)

watch(
  () => conversationStore.currentConversation.conversationID,
  (val, prevCount) => {
    console.log(val, prevCount, 'ssssssss')
    let cleanText = messageContent.value
    const atEls = getAtList()

    if (messageContent.value && prevCount) {
      if (atEls.length > 0) {
        atEls.map((el) => (cleanText = cleanText.replace(el.tag, `@${el.userID} `)))
        const pattern = /@\S+\s/g
        const arr = cleanText.match(pattern)
        arr?.map((item) => {
          const member = atEls.find((el) => el.userID === item.slice(1, -1))
          if (member) {
            const reg = new RegExp(item, 'g')
            cleanText = cleanText.replace(
              reg,
              `<b class="at_el" contenteditable="false" data_id="${member.userID}" data_name="${member.nickname}">@${member.nickname} </b>`,
            )
          }
        })
      }
    }
  },
  {
    immediate: true,
  },
)

onMounted(() => {
  if (!inputRef.value) return
  inputRef.value.inputRef.focus()
})

onActivated(() => {
  if (!inputRef.value) return
  inputRef.value.clear()
  inputRef.value.inputRef.focus()
})
</script>

<style lang="scss" scoped>
:deep(.van-button__content) {
  width: max-content;
}
</style>
